<template>
  <view class="ad-banner">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <text>加载广告中...</text>
    </view>
    
    <!-- 广告内容 -->
    <view v-else-if="ads.length > 0" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: transparent; display: flex; align-items: center; justify-content: center;">
      <!-- 广告图片 -->
      <image 
        :src="getAdImageUrl(ads[0])" 
        mode="aspectFill" 
        style="width: 100% !important; height: 100% !important; position: absolute !important; top: 0 !important; left: 0 !important; z-index: 999 !important; background: transparent !important; display: block !important;"
        @load="onImageLoad(ads[0].id)"
        @error="onImageError(ads[0].id)"
      />
      <view class="ad-text">
        <text class="ad-title">{{ ads[0].adName }}</text>
        <text class="ad-desc">{{ getAdDescription(ads[0]) }}</text>
      </view>
    </view>

    <!-- 无广告状态 -->
    <view v-else class="no-ads">
      <text>暂无广告</text>
    </view>
  </view>
</template>

<script>
import { getBannerAds, recordAdClick, recordAdView } from '@/api/ad'

export default {
  name: 'AdBanner',
  props: {
    positionCode: {
      type: String,
      default: 'BANNER'
    }
  },
  data() {
    return {
      ads: [],
      loading: false
    }
  },
  mounted() {
    this.loadAds()
  },
  methods: {
    async loadAds() {
      try {
        this.loading = true
        console.log('开始加载广告...')
        
        // 调用API获取广告数据
        const res = await getBannerAds()
        console.log('广告API响应:', res)
        
        if (res.code === 200 && res.data && res.data.length > 0) {
          // 处理API返回的数据，为空的contents添加默认图片
          this.ads = this.processAdData(res.data)
          console.log('处理后的广告数据:', this.ads)
          // 记录所有广告的展示
          this.recordAdViews()
          
          // 强制刷新组件
          this.$nextTick(() => {
            console.log('强制刷新广告组件')
            this.$forceUpdate()
          })
        } else {
          console.warn('广告API返回异常或无数据，使用测试数据:', res)
          // 使用测试数据
          this.ads = this.getTestAds()
        }
      } catch (error) {
        console.error('加载广告失败，使用测试数据:', error)
        console.error('错误详情:', {
          message: error.message,
          stack: error.stack,
          response: error.response
        })
        // 使用测试数据
        this.ads = this.getTestAds()
      } finally {
        this.loading = false
      }
    },
    
    // 处理API返回的广告数据
    processAdData(adsData) {
      console.log('原始广告数据:', adsData)
      
      const bannerImages = [
        './static/images/banner/banner01.jpg',
        './static/images/banner/banner02.jpg',
        './static/images/banner/banner03.jpg'
      ]
      
      const processedAds = adsData.map((ad, index) => {
        console.log(`处理广告 ${ad.id}:`, ad)
        
        // 优先使用redirectLink作为图片URL
        if (ad.redirectLink) {
          let imageUrl = ad.redirectLink
          // 检查URL是否以图片扩展名结尾，如果不是则添加.jpg
          if (!imageUrl.match(/\.(jpg|jpeg|png|gif|webp)$/i)) {
            imageUrl += '.jpg'
          }
          console.log(`广告 ${ad.id} 使用redirectLink作为图片: ${imageUrl}`)
          ad.contents = [
            {
              id: ad.id || index + 1,
              contentUrl: imageUrl,
              contentName: ad.adName + '主图'
            }
          ]
        } else if (!ad.contents || ad.contents.length === 0) {
          console.log(`广告 ${ad.id} 的contents为空且无redirectLink，使用默认图片`)
          
          let imageUrl = bannerImages[index % bannerImages.length]
          
          ad.contents = [
            {
              id: ad.id || index + 1,
              contentUrl: imageUrl,
              contentName: ad.adName + '主图'
            }
          ]
        }
        
        console.log(`广告 ${ad.id} 处理后的数据:`, ad)
        return ad
      })
      
      console.log('处理完成后的广告数据:', processedAds)
      return processedAds
    },
    
    // 获取测试广告数据
    getTestAds() {
      return [
        {
          id: 1,
          adName: '每日推荐广告',
          displayForm: 2,
          intervalTime: 3,
          redirectLink: 'https://picsum.photos/400/200?random=1',
          contents: [
            {
              id: 1,
              contentUrl: 'https://picsum.photos/400/200?random=1',
              contentName: '每日推荐主图'
            }
          ]
        },
        {
          id: 2,
          adName: '新品推荐广告',
          displayForm: 2,
          intervalTime: 3,
          redirectLink: 'https://picsum.photos/400/200?random=2',
          contents: [
            {
              id: 2,
              contentUrl: 'https://picsum.photos/400/200?random=2',
              contentName: '新品推荐主图'
            }
          ]
        },
        {
          id: 3,
          adName: '限时优惠广告',
          displayForm: 2,
          intervalTime: 3,
          redirectLink: 'https://picsum.photos/400/200?random=3',
          contents: [
            {
              id: 3,
              contentUrl: 'https://picsum.photos/400/200?random=3',
              contentName: '限时优惠主图'
            }
          ]
        }
      ]
    },
    
    // 获取广告图片URL
    getAdImageUrl(ad) {
      let imageUrl = ''
      
      // 优先使用redirectLink作为图片URL
      if (ad.redirectLink) {
        imageUrl = ad.redirectLink
        // 检查URL是否以图片扩展名结尾，如果不是则添加.jpg
        if (!imageUrl.match(/\.(jpg|jpeg|png|gif|webp)$/i)) {
          imageUrl += '.jpg'
        }
        console.log(`使用redirectLink作为图片URL: ${imageUrl}`)
      } else if (ad.contents && ad.contents.length > 0 && ad.contents[0].contentUrl) {
        imageUrl = ad.contents[0].contentUrl
        console.log(`使用contents中的图片URL: ${imageUrl}`)
      } else {
        // 最后使用默认图片
        const bannerImages = [
          './static/images/banner/banner01.jpg',
          './static/images/banner/banner02.jpg',
          './static/images/banner/banner03.jpg'
        ]
        imageUrl = bannerImages[ad.id % bannerImages.length] || bannerImages[0]
        console.log(`使用默认图片: ${imageUrl}`)
      }
      
      console.log(`广告 ${ad.id} 最终图片URL: ${imageUrl}`)
      return imageUrl
    },
    
    // 获取广告描述
    getAdDescription(ad) {
      if (ad.contents && ad.contents.length > 0 && ad.contents[0].contentName) {
        return ad.contents[0].contentName
      }
      return ad.adName || '广告'
    },
    
    async handleAdClick(ad) {
      try {
        console.log('点击广告:', ad)
        // 记录点击
        await recordAdClick(ad.id)
        
        // 跳转链接
        if (ad.redirectLink) {
          // 判断是内部页面还是外部链接
          if (ad.redirectLink.startsWith('/pages/')) {
            uni.navigateTo({
              url: ad.redirectLink
            })
          } else {
            // 外部链接，复制到剪贴板或打开浏览器
            uni.setClipboardData({
              data: ad.redirectLink,
              success: () => {
                uni.showToast({
                  title: '链接已复制',
                  icon: 'success'
                })
              }
            })
          }
        }
      } catch (error) {
        console.error('处理广告点击失败:', error)
      }
    },
    
    onImageLoad(adId) {
      console.log('广告图片加载成功:', adId)
      // 图片加载完成时记录展示
      this.recordAdView(adId)
    },
    
    onImageError(adId) {
      console.error('广告图片加载失败:', adId)
      // 尝试使用本地图片作为备用
      const ad = this.ads.find(a => a.id === adId)
      if (ad) {
        console.log(`广告 ${adId} 图片加载失败，尝试使用本地备用图片`)
        const bannerImages = [
          './static/images/banner/banner01.jpg',
          './static/images/banner/banner02.jpg',
          './static/images/banner/banner03.jpg'
        ]
        // 强制更新图片URL为本地图片
        if (ad.contents && ad.contents.length > 0) {
          ad.contents[0].contentUrl = bannerImages[adId % bannerImages.length] || bannerImages[0]
          console.log(`更新广告 ${adId} 图片URL为: ${ad.contents[0].contentUrl}`)
          // 强制刷新组件
          this.$forceUpdate()
        }
      }
    },
    
    onSwiperChange(e) {
      // 轮播切换时记录展示
      const currentAd = this.ads[e.detail.current]
      if (currentAd) {
        this.recordAdView(currentAd.id)
      }
    },
    
    async recordAdViews() {
      // 记录所有广告的展示
      for (const ad of this.ads) {
        await this.recordAdView(ad.id)
      }
    },
    
    async recordAdView(adId) {
      try {
        await recordAdView(adId)
      } catch (error) {
        console.error('记录广告展示失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.ad-banner {
  width: 100% !important;
  height: 120px !important;
  border-radius: 12px !important;
  overflow: visible !important;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  background: transparent !important;
  position: relative !important;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: rgba(255, 255, 255, 0.8);
  font-size: 28rpx;
  background: transparent;
}

.no-ads {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: rgba(255, 255, 255, 0.8);
  font-size: 28rpx;
  background: transparent;
}

.single-ad {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 20rpx;
  overflow: hidden;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
}

.swiper-ad {
  width: 100%;
  height: 100%;
  border-radius: 12px;
  background: transparent;
}

.swiper-item {
  width: 100% !important;
  height: 100% !important;
  position: relative !important;
  overflow: visible !important;
  background: transparent !important;
  display: block !important;
}

.ad-image {
  width: 100% !important;
  height: 100% !important;
  transition: transform 0.3s ease;
  display: block !important;
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  z-index: 999 !important;
  background: transparent !important;
  border: 5px solid yellow !important;
}

.single-ad:active .ad-image,
.swiper-item:active .ad-image {
  transform: scale(1.05);
}

.ad-text {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 30rpx;
  color: #fff;
  backdrop-filter: blur(10px);
  z-index: 15;
}

.ad-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 12rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.ad-desc {
  display: block;
  font-size: 26rpx;
  opacity: 0.9;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
}


</style>